package service

import (
	"fmt"

	"gitee.com/gomaster/book-library/entity"
	"gitee.com/gomaster/book-library/repo"
	"github.com/gin-gonic/gin"
)

// InitUserHandler 初始化用户操作
func InitUserHandler(r *gin.Engine) {
	ur := r.Group("/user")
	ur.POST("/add", AddUser)
	ur.POST("/del/:name", DelUser)
	ur.POST("/update/:name", UpdateUser)
	ur.POST("/get/:name", GetUser)
}

// AddUser 新增加用户
func AddUser(c *gin.Context) {
	user := &entity.UserInfo{}
	err := c.BindJSON(user)
	if err != nil {
		fmt.Printf("parse param failed, err:%s", err.Error())
		entity.ReturnFail(c, "param invalid")
		return
	}

	handler := repo.GetRepoHandler()
	userInfo := handler.UserGet(user.Name)
	if userInfo != nil {
		fmt.Printf("user has exist already, userName:%s", user.Name)
		entity.ReturnFail(c, "user exist already")
		return
	}

	err = handler.UserAdd(user)
	if err != nil {
		fmt.Printf("add user failed, err:%s", err.Error())
		entity.ReturnFail(c, "add user failed")
		return
	}
	entity.ReturnOK(c, nil)
}

// DelUser 删除用户
func DelUser(c *gin.Context) {
	userName := c.Param("name")
	if userName == "" {
		return
	}
	handler := repo.GetRepoHandler()
	err := handler.UserDel(userName)
	if err != nil {
		fmt.Printf("user delete failed, userName:%s, err:%s", userName, err.Error())
		entity.ReturnFail(c, "delete failed")
		return
	}
	entity.ReturnOK(c, nil)
}

// UpdateUser 更新用户
func UpdateUser(c *gin.Context) {
	userName := c.Param("name")

	userInfo := &entity.UserInfo{}
	err := c.BindJSON(userInfo)
	if err != nil {
		fmt.Printf("parse request failed, err:%s", err.Error())
		entity.ReturnFail(c, "parse request failed, "+err.Error())
		return
	}

	handler := repo.GetRepoHandler()
	err = handler.UserUpdate(userName, userInfo)
	if err != nil {
		fmt.Printf("update user failed, user:%s, err:%s", userName, err.Error())
		entity.ReturnFail(c, err.Error())
		return
	}
	entity.ReturnOK(c, nil)
}

// GetUser 查询用户
func GetUser(c *gin.Context) {
	user := c.Param("name")
	if user == "" {
		fmt.Printf("user name is null")
		entity.ReturnFail(c, "user name is null")
		return
	}
	handler := repo.GetRepoHandler()
	userInfo := handler.UserGet(user)
	entity.ReturnOK(c, userInfo)
}
